#!/usr/bin/python
# -*- coding: utf-8 -*-
#@classmethod @staticmethod

import requests
import os
import logging

class fileUploadClass:

    def __init__(self, filePath, uploadUrl):
        self.uploadUrl = uploadUrl
        self.filePath = filePath

    def __del__(self):
        pass


    #这段上传文件代码需要修改为分块读取并进行上传的方式，一次性读取文件耗费内存太大
    #此段代码针对小于50M的视频文件进行读取，属于一次性读取，进行分片上传，如果大于50M那么不能用这个函数
    # @staticmethod
    # def startFileUpload(filePath, uploadUrl):
    #     videoFile = open(filePath, "rb")
    #     videoData = videoFile.read()
    #     videoFile.close()
    #     file_size = len(videoData)  # 视频文件总长度
    #     chunk_size = 1 * 1024 * 1024  # 每个分片大小，1M（可根据需要自定义分片大小）
    #     i = 0
    #     start = 0  # 分片开始位置
    #     end = 0  # 分片结束文章
    #     # 2. 分片上传
    #     while end < file_size:
    #         start = i * chunk_size
    #         end = start + chunk_size
    #
    #         if end > file_size:
    #             end = file_size
    #
    #         payload = {'video_file': videoData[start:end]}
    #         headers = {'Content-Range': 'bytes %s-%s/%s' % (start, end - 1, file_size)}  # header中必须有Content-Range
    #         send_video = requests.post(uploadUrl, files=payload, headers=headers)
    #         print(send_video.status_code)
    #         print '------------------------------------'
    #         print(send_video.text)
    #         print '------------------------------------'
    #         print(send_video.headers)
    #         print '------------------------------------'
    #
    #         if 200 != send_video.status_code:
    #             return '1'
    #
    #         i = i + 1
    #
    #     print '文件上传成功'
    #     return '0'


    #此段代码针对大于50M的视频文件进行分片上传，针对服务器内存和CPU性能进行了优化
    def read_in_chunks(self, filePath, chunk_size=1024 * 1024):
        file_object = open(filePath)
        while True:
            chunk_data = file_object.read(chunk_size)
            if not chunk_data:
                break
            yield chunk_data

    def get_FileSize(self, filePath):
        filePath = unicode(filePath, 'utf8')
        return os.path.getsize(filePath)

    def startBigFileUpload(self):

        logging.debug('startBigFileUpload')

        if (len(self.filePath) == 0) or (len(self.uploadUrl) == 0) or (self.filePath is None) or (self.uploadUrl is None):
            logging.debug('文件路径或url获取错误')
            return 1

        logging.debug('filePath = %s', self.filePath)
        file_size = self.get_FileSize(self.filePath)  # 视频文件总大小
        logging.debug('fileSize = %d', file_size)

        chunk_size = 1 * 1024 * 1024  # 每个分片大小，1M（可根据需要自定义分片大小）
        i = 0
        start = 0  # 分片开始位置
        end = 0  # 分片结束文章

        # 2. 分片上传
        for chunk in self.read_in_chunks(self.filePath):
            start = i * chunk_size
            end = start + chunk_size

            if end > file_size:
                end = file_size

            payload = {'video_file': chunk}
            headers = {'Content-Range': 'bytes %s-%s/%s' % (start, end - 1, file_size)}
            send_video = requests.post(self.uploadUrl, files=payload, headers=headers)
            logging.debug('status_code = %d, send_video = %s', send_video.status_code, send_video.text)
            if 200 != send_video.status_code:
                return 1

            i = i + 1
        return 0